<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <link rel="stylesheet" href="../css/search.css">
    <script src="../js/cookie.js"></script>
    <script src="../js/ajax.js"></script>
    <style>
        .w {
            width: 1226px;
            margin: 0 auto;
        }

        .header {
            height: 45px;
            line-height: 45px;
            font-size: 14px;
        }

        .showGrade {
            min-height: 270px;
        }

        .showGrade table {
            width: 100%;
            table-layout: fixed;
            border: 1px solid #666;
            border-spacing: 0;
            border-collapse: collapse;
            line-height: 36px;
            text-align: center;

        }

        .showGrade table th,
        .showGrade table td {
            border: 1px solid #666;
        }

        .shadow {
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            position: fixed;
            left: 0;
            top: 0;
            display: none;
        }

        .shadow form {
            padding: 20px;
            background-color: #fff;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        .shadow form p+p {
            margin-top: 8px;
        }
    </style>
</head>

<body>
    <div class="header w">
        <div class="tipsBar">
            <a href="./login.html">亲,请登录</a>
            <a href="./register.html">用户注册</a>
        </div>
    </div>
    <form class="search_bar w" onsubmit="return false">
        <div class="searchBox">
            <input type="text" class="searchCon">
            <button class="searchBtn">搜索</button>
        </div>
        <div class="orderBox">
            <!-- 排序的列(column)名 (id,chinese,math,english,total) -->
            <div class="orderColBox">
                <label>
                    学号
                    <input type="radio" checked="" name="orderCol" class="orderCol" value="id">
                </label>
                <label>
                    语文
                    <input type="radio" name="orderCol" class="orderCol" value="chinese">
                </label>
                <label>
                    数学
                    <input type="radio" name="orderCol" class="orderCol" value="math">
                </label>
                <label>
                    英语
                    <input type="radio" name="orderCol" class="orderCol" value="english">
                </label>
                <label>
                    总分
                    <input type="radio" name="orderCol" class="orderCol" value="total">
                </label>
            </div>
            <!-- 排序的类型  升序 / 降序 -->
            <div class="orderTypeBox">
                <label>
                    升序
                    <input type="radio" checked="" name="orderType" class="orderType" value="asc">
                </label>
                <label>
                    降序
                    <input type="radio" name="orderType" class="orderType" value="desc">
                </label>
            </div>
            <div class="showNumBox">
                <select class="select">
                    <option value="5" selected="">每页显示05条</option>
                    <option value="10">每页显示10条</option>
                    <option value="15">每页显示15条</option>
                    <option value="20">每页显示20条</option>
                </select>
            </div>
            <input type="reset" class="resetBtn" value="重置">
        </div>
    </form>
    <div class="showGrade w">
        <table>
            <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>班级</th>
                    <th>语文</th>
                    <th>数学</th>
                    <th>英语</th>
                    <th>总分</th>
                    <th>编辑</th>
                    <th>删除</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>张三</td>
                    <td>2108</td>
                    <td>55</td>
                    <td>66</td>
                    <td>77</td>
                    <td>198</td>
                    <td><a href="javascript:;" class="edit">编辑</a></td>
                    <td><a href="javascript:;" class="edit">删除</a></td>
                </tr>
            </tbody>
        </table>
        <div class="pageBox">
            <button class="prev">上一页</button>
            <span class="pageTips"></span>
            <button class="next">下一页</button>
        </div>
    </div>
    <div class="shadow">
        <form class="gradeDetail" onsubmit="return false">
            <p><label>编号:<input type="text" name="id" disabled></label></p>
            <p><label>姓名:<input type="text" name="name" disabled></label></p>
            <p><label>班级:<input type="text" name="class" disabled></label></p>
            <p><label>语文:<input type="text" name="chinese"></label></p>
            <p><label>数学:<input type="text" name="math"></label></p>
            <p><label>英语:<input type="text" name="english"></label></p>
            <p>
                <input type="submit" class="save" value="保存">
                <input type="reset" class="cancel" value="取消">
            </p>
        </form>
    </div>
</body>
<script>
    var tipsBar = document.getElementsByClassName("tipsBar")[0];
    var showGrade = document.getElementsByClassName("showGrade")[0];
    var tbody = showGrade.getElementsByTagName("tbody")[0];
    var shadow = document.getElementsByClassName("shadow")[0];
    var form = document.getElementsByClassName("gradeDetail")[0];
    var save = document.getElementsByClassName("save")[0];
    var cancel = document.getElementsByClassName("cancel")[0];

    var search_bar = document.getElementsByClassName("search_bar")[0];
    var searchCon = document.getElementsByClassName("searchCon")[0];

    var prev = document.getElementsByClassName("prev")[0];
    var next = document.getElementsByClassName("next")[0];
    var pageTips = document.getElementsByClassName("pageTips")[0];
    var select = document.getElementsByClassName("select")[0];

    // var idInput = document.getElementsByName("id")[0];
    // var nameInput = document.getElementsByName("name")[0];
    // var classInput = document.getElementsByName("class")[0];
    // var chineseInput = document.getElementsByName("chinese")[0];
    // var mathInput = document.getElementsByName("math")[0];
    // var englishInput = document.getElementsByName("english")[0];

    // 拓展: 可以通过form表单 获取对应字段名(name)的元素
    // console.log(form.id);
    // console.log(form.name);
    // console.log(form.class);
    // console.log(form.chinese);
    // console.log(form.math);
    // console.log(form.english);


    // 声明全局变量  =>赋予默认值
    var key = "";    // "" 默认查询所有数据
    var orderCol = "id";   // 默认按照id排
    var orderType = "asc"; //默认升序
    var pageIndex = 1;   // 默认显示第一页  => 记录切换后的页码
    var showNum = 5;     //每页显示多少条


    // 标识用户身份
    var cookie = document.cookie;
    if (cookie) {
        var user = getCookie("lgc");  //登录的用户名
        if (user) {
            tipsBar.innerHTML = `<span>欢迎您,${user}</span><button onclick="exit()">退出</button>`;
        }
    }

    // 页面加载时 => 请求数据 渲染到表格中
    loadGrade();
    function loadGrade() {
        $.ajax({
            type: "get",
            url: "../php/searchGradeOrderLimit.php",
            // 找全局
            data: { key, orderCol, orderType, pageIndex, showNum },
            dataType: "json",
            success: function (result) {
                console.log(result);
                var { status, msg, maxPage, count, currentPage, list } = result;

                // 每页显示5条  到  每页显示 10条  => 切换时 每页显示5条 最大页) 超出 (每页显示 10条 最大页)  => 切换又问题 
                // 怎么解决? 
                // 判断 pageIndex 是否大于最大页  大于:超出=>只显示到最大页  小于:不超出 正常显示
                pageIndex = pageIndex > maxPage ? maxPage : pageIndex;

                if (status) {
                    if (list.length > 0) {
                        var html = "";
                        list.forEach(({ id, name, class: _class, chinese, math, english, total }) => {
                            html += `<tr data-id="${id}" data-index="hello">
                            <td>${id}</td>
                            <td>${name}</td>
                            <td>${_class}</td>
                            <td>${chinese}</td>
                            <td>${math}</td>
                            <td>${english}</td>
                            <td>${total}</td>
                            <td><a href="javascript:;" class="edit">编辑</a></td>
                            <td><a href="javascript:;" class="delete">删除</a></td>
                            </tr>`
                        });
                        // console.log(html);
                        tbody.innerHTML = html;
                        pageTips.innerHTML = `${pageIndex}/${maxPage}`;

                        // if (pageIndex == 1) {
                        //     prev.style.display = "none";
                        // } else if (pageIndex == maxPage) {
                        //     next.style.display = "none";
                        // } else {
                        //     prev.style.display = "block";
                        //     next.style.display = "block";
                        // }

                        prev.onclick = function () {
                            if (pageIndex <= 1) return false;
                            pageIndex--;
                            loadGrade();
                        }
                        next.onclick = function () {
                            if (pageIndex >= maxPage) return false;
                            pageIndex++;
                            loadGrade();
                        }


                    } else {
                        tbody.innerHTML = "<tr><td colspan='9'>暂无数据</td></tr>";
                    }

                } else {
                    alert(msg);
                }


            }
        })
    }



    search_bar.onclick = function (e) {
        var e = e || window.event;
        var target = e.target || e.srcElement;
        if (target.className == "searchBtn") {
            key = searchCon.value.trim();
            loadGrade();
        } else if (target.className == "orderCol") {
            orderCol = target.value;
            loadGrade();
        } else if (target.className == "orderType") {
            orderType = target.value;
            loadGrade();
        } else if (target.className == "resetBtn") {
            key = "";    // "" 默认查询所有数据
            orderCol = "id";   // 默认按照id排
            orderType = "asc"; //默认升序
            pageIndex = 1;   // 默认显示第一页  => 记录切换后的页码
            showNum = 5;     //每页显示多少条
            loadGrade();
        }
    }

    select.onchange = function () {
        showNum = this.value;
        loadGrade();
    }

    // 事件委托绑定事件  
    tbody.onclick = function (e) {
        var e = e || window.event;
        var target = e.target || e.srcElement;

        if (target.className == "delete") {
            console.log("点击了删除", target);
            if (confirm("是否删除该数据")) {
                deleteOneHandler(target);
            }
        } else if (target.className == "edit") {
            editHandler(target);
        }
    }
    save.onclick = function () {
        var id = form.id.value;       // idInput.value
        var ch = form.chinese.value;  // chineseInput.value
        var mh = form.math.value;      // mathInput.value
        var en = form.english.value;  // englishInput.value

        var xhr = new XMLHttpRequest();

        xhr.open("post", "../php/updateGradeById.php", true);

        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(`id=${id}&ch=${ch}&mh=${mh}&en=${en}`);

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
                console.log(result);
                var data = JSON.parse(result);
                console.log(data);
                var { status, msg } = data;
                if (status) {
                    shadow.style.display = "none";
                    loadGrade(); // 在不提交整个页面的情况下 实现页面的局部刷新
                } else {
                    alert(msg);
                }
            }
        }

    }
    cancel.onclick = function () {
        shadow.style.display = "none";
    }




    function deleteOneHandler(target) {
        var tr = target.parentElement.parentElement;

        //  属性节点的查找
        // var id = tr.getAttribute("data-id");
        // console.log(id);

        // 拓展  对于H5 新增的自定义属性(data-xxx)  存在元素节点的属性 dataset 获取所有的data-xxx开头的属性
        // console.dir(tr);

        var id = tr.dataset.id;

        var xhr = new XMLHttpRequest();

        xhr.open("get", "../php/deleteGradeById.php?ids=" + id, true);

        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
                console.log(result);
                var data = JSON.parse(result);
                console.log(data);
                var { status, msg } = data;
                if (status) {
                    tr.remove();
                } else {
                    alert(msg);
                }

            }
        }

    }

    function editHandler(target) {
        shadow.style.display = "block";
        var tr = target.parentElement.parentElement;
        var id = tr.dataset.id;
        console.log(id);

        var xhr = new XMLHttpRequest();

        xhr.open("get", "../php/searchGradeById.php?id=" + id, true);

        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
                // console.log(result);
                var obj = JSON.parse(result);
                console.log(obj);
                var { status, msg, data } = obj;

                // form.id === idInput
                // form.id.value  === idInput.value;


                // form.id.value = data.id;
                // form.name.value = data.name;
                // form.class.value = data.class;
                // form.chinese.value = data.chinese;
                // form.math.value = data.math;
                // form.english.value = data.english;

                for (var key in data) { // key => "id","name","class"
                    form[key].value = data[key];
                }

            }
        }
    }


    function parent(ele) {
        return ele.parentElement || ele.parentNode;
    }
    function prev(ele) {
        return ele.previousElementSibling || ele.previousSibling;
    }
    function next(ele) {
        return ele.nextElementSibling || ele.nextSibling;
    }


    function exit() {
        delCookie("lgc");
        location.reload();
    }




</script>

</html>